import React, { useRef, useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { ModalForm, PageContainer, ProFormText, ProTable, ProFormUploadButton,ProFormCascader } from '@ant-design/pro-components';
import { Button, message, Image, Popconfirm, Form } from 'antd';
import _ from '@/assets/utils';
import MODEL_API from '@/services/model';
import styled from 'styled-components';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { history, useSearchParams } from '@umijs/max';
// import { SmileOutlined } from '@ant-design/icons';
import {
  ProForm,
  ProFormDigit,
  ProFormRadio,
  ProFormTextArea,
} from '@ant-design/pro-components';

const StyleBox = styled.div`
 .ant-btn {
        color: #fff;
        background-color: #1baeae;
    border-color: #1baeae;
    border-radius: 4px!important;
    width: 97px;
    height: 40px;
    margin-left: 60px;
    &:hover{
      border-color: #49bebe;
    background-color: #49bebe;
    }
    }
    .ant-input-affix-wrapper {
      width: 300px!important;
      height: 40px;
      border-radius: 4px!important;
    border: 1px solid #dcdfe6;
    color: #606266;
    box-sizing: border-box;
    padding: 0 15px;
    .ant-input {
      height: 38px!important;
    }
    }
    .ant-input{
      padding: 5px 15px;
      width: 300px!important;
      height: 53.6px!important;
    }
    .ant-input-number {
      width: 300px!important;
      height: 40px!important;
   box-sizing:border-box!important;
       padding-top: 5px;
  }
  .ant-space {
    position: relative;
    top: 60px;
  }
  .ant-form-item-explain-error {
    font-size:12px;
  }
.ant-select {
  width: 300px!important;
      .ant-select-selector{
        height: 40px!important;
      }
      .ant-select-selection-search{
        height: 40px!important;
        line-height: 40px!important;
      }
      
}
`;
const OneBox = styled.div`
label {
  position: absolute;
    left: 8px;
}
  .ant-form-item-control-input-content{
    position: absolute;
    left: 10px;
  }
  .ant-form-item-control-input-content{
   margin-top: 13px; 
 }
`;
const TwoBox = styled.div`
  .ant-input-number  {
      width: 286px!important;
  }
`;
const ThreeBox = styled.div`
  .ant-input-affix-wrapper   {
      position: relative;
    left: 10px;
  
  }
`;

const FourBox = styled.div`
   .ant-form-item-control-input-content{
   margin-top: 13px; 
 }
 label {
  margin-top: 13px; 
}
`;

const Add = function Add() {
  const [focus, setFocus] = useState(null);
  const [id, setId] = useState(null);
  const [options, setOptions] = useState([]);
  // const [jeck, setJeck] = useState(null);
  const [goodsCategoryId
    , setGoodsCategoryId] = useState(2412);
  const [usp] = useSearchParams(),
    [fileList, setFileList] = useState([]),//图片的
    modelFormIns = useRef();

  useEffect(() => {
    (async () => {
      let to = usp.get('to');
      if (to) {
        let { resultCode, data } = await MODEL_API.modifyList(to);
        if (+resultCode === 200) {
          let { goods, secondCategory,firstCategory,thirdCategory
          } = data;
      
          let { goodsCategoryId, goodsId, goodsName, goodsIntro, originalPrice, sellingPrice, stockNum, tag, goodsSellStatus, goodsCoverImg, goodsDetailContent } = goods;
          let { categoryName:nameOne} = firstCategory
          ;
          let { categoryName:nameTwo } = secondCategory;
          let { categoryName:nameThree } = thirdCategory;
          setId(`${goodsId}`);
          
          setGoodsCategoryId(goodsCategoryId);
          modelFormIns.current.setFields([
           {
            name: 'goodsCategoryId',
            value: `${nameOne}/${nameTwo}/${nameThree}`
           } ,{
            name: 'goodsName',
            value: goodsName
          }, {
            name: 'goodsIntro',
            value: goodsIntro
          }, {
            name: 'originalPrice',
            value: originalPrice
          }, {
            name: 'sellingPrice',
            value: sellingPrice
          }, {
            name: 'stockNum',
            value: stockNum
          }, {
            name: 'tag',
            value: tag
          }, {
            name: 'goodsDetailContent',
            value: goodsDetailContent
          }, {
            name: 'goodsCoverImg',
            value: goodsCoverImg
          }
            , {
            name: 'goodsSellStatus',
            value: goodsSellStatus
          }
          ]);
          setFileList([{
            url: goodsCoverImg
          }]);
        }
      }
    })();
  }, []);
  /* 级联选择器 */
  const loadData = async (selectedOptions) => {
    let targetOption = selectedOptions[selectedOptions.length - 1],
      { level, value, } = targetOption;
   
    if (level < 3) {
      targetOption.loading = true;
      let children = await queryTableData(1000, 1, level + 1, value);
      targetOption.children = children;
      targetOption.loading = false;
      // targetOption = targetOption[targetOption.length-1]
      setOptions([...options]);
    }
  };
  useEffect(() => {
    (async () => {
      let options = await queryTableData(100, 1, 1, 0);
      setOptions(options);
    })();
  }, []);
  const queryTableData = async (pageSize, current, categoryLevel, parentId) => {
    let options = [];
    try {
      let { resultCode, data } = await MODEL_API.classifyList(current, pageSize, categoryLevel, parentId);
      if (+resultCode === 200) {
        options = data.list.map(item => {
          return {
            label: item.categoryName,
            value: item.categoryId,
            loading: false,
            level: categoryLevel,
            isLeaf: categoryLevel >= 3
          };
        });
      }
    } catch (_) { }
    return options;
  };
  /* 文件上传的方法 */
  const onBeforeUpload = ({ size }) => {
    if (size > 1024 * 1024) {
      message.warning('上传的图片不能超过1MB大小~');
      return false;
    }
    return true;
  };
  const onUploadChange = ({ file, fileList }) => {
    let response = file?.response,
      status = file?.status;
    if (status === 'done' && response) {
      let { resultCode, data } = response;
      if (+resultCode === 200) {
        modelFormIns.current.setFieldValue('goodsCoverImg', data);
      }
    }
    if (status === "removed") {
      modelFormIns.current.setFieldValue('goodsCoverImg', "");
    }
    setFileList(fileList);
  };
  const submit = async (values) => {
    let to = usp.get('to'), tip;
    if (to) {
      tip = '修改';
      values.goodsId = id;
      values.goodsCategoryId = goodsCategoryId;
     
      try {
        let { resultCode } = await MODEL_API.addList(values);
        if (+resultCode !== 200) {
          message.error(`很遗憾，${tip}失败，`);
          return;
        }
        message.success(`恭喜您，${tip}成功`);
        history.push({
          pathname: '/modulars/goods',
        });
      } catch (_) { }
    } else {
      tip = '新增';
      values.goodsCategoryId = goodsCategoryId;
      
      try {
        let { resultCode } = await MODEL_API.newList(values);
        if (+resultCode !== 200) {
          message.error(`很遗憾，${tip}失败，`);
          return;
        }
        message.success(`恭喜您，${tip}成功`);
        history.push({
          pathname: '/modulars/goods',
        });
      } catch (_) { }
    }

  };

  
  return <PageContainer>
    <StyleBox>
      <ProForm
        onFinish={submit}
        layout={'horizontal'}
        formRef={modelFormIns}
        submitter={{
          // 配置按钮文本
          searchConfig: {
            resetText: '重置',
            submitText: '提交',
          },
          // 配置按钮的属性
          resetButtonProps: {
            style: {
              // 隐藏重置按钮
              display: 'none'
            }
          }
        }}
      >
        {/* 商品分类 */}
        <ProFormCascader
            label="商品分类"
            width='md'
            name="goodsCategoryId"
            rules={[{ required: true, message: '分类不能为空' }]}
            fieldProps={{
              options,
              loadData,
              changeOnSelect: true
            }}
          />
        {/*商品名称  */}
        <ProFormText
          width="md"
          name="goodsName"
          label="商品名称"
          placeholder="请输入商品名称"
          rules={[
            { required: true, message: '请填写商品名称' }
          ]}
        />

        <OneBox>
          <ProFormTextArea width="xl" label="商品简介" name="goodsIntro" placeholder="请输入商品简介（100字）" />
        </OneBox>

        <FourBox>
          <ProFormDigit width="xs" name="originalPrice" label="商品价格" placeholder="请输入商品价格" rules={[
            { required: true, message: '请填写商品价格' }
          ]} />
        </FourBox>

        <TwoBox>
          <ProFormDigit width="xs" name="sellingPrice" label="商品售卖价" initialValue={''} placeholder="请输入商品售价" rules={[
            { required: true, message: '请填写商品售价' }
          ]} />
        </TwoBox>

        <ProFormDigit class='aaa' width="xs" name="stockNum" label="商品库存" initialValue={''} placeholder="请输入商品库存" rules={[
          { required: true, message: '请填写商品库存' }
        ]} />

        <ThreeBox>
          <ProFormText
            width="md"
            name="tag"
            label="商品标签"
            placeholder="请输入商品小标签"
          />
        </ThreeBox>

        <ProFormRadio.Group
          label="上架状态"
          name="goodsSellStatus"
          options={[
            {
              label: '上架',
              value: 0,
            },
            {
              label: '下架',
              value: 1,
            }
          ]}
          fieldProps={{
            defaultValue: 0
          }}
        />


        <ProFormUploadButton name="goodsCoverImg"
          label="上传图片"
          rules={[
            { required: true, message: '请上传主图' }
          ]}
          max={1}
          fieldProps={{
            action: '/api/upload/file',
            headers: {
              token: _.storage.get('tk')
            },
            accept: 'image/*',
            listType: 'picture-card',
            fileList,
            beforeUpload: onBeforeUpload,
            onChange: onUploadChange
          }}
        />


        <Form.Item label='详情内容' name='goodsDetailContent'>
          <ReactQuill
            theme="snow"
            placeholder='请输入正文'
            style={{ width: '1174px', height: '300px' }}
          />
        </Form.Item>
      </ProForm>
    </StyleBox>
  </PageContainer >;
};
export default Add;